package timetable.student;

import static timetable.student.Constants.DAY;
import static timetable.student.Constants.LECTURER;
import static timetable.student.Constants.MODULE;
import static timetable.student.Constants.ROOM;
import static timetable.student.Constants.TABLE_NAME;
import static timetable.student.Constants.TIMEEND;
import static timetable.student.Constants.TIMESTART;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class AddClass extends Activity {
	private TimeTableData events;
	private EditText module;
	private int day;
	private Spinner spinner;
	private EditText room;
	private EditText lecturer;
	private Button startPicker;
	private Button endPicker;
	private Button cancelBtn;
	private int startHour;
	private int startMin;
	private int endHour;
	private int endMin;
	static final int STIME_DIALOG_ID = 0;	
	static final int ETIME_DIALOG_ID = 1;
	private boolean update = false;
	private String _id = "-1";
	String[] temp = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.add);
	    spinner = (Spinner) findViewById(R.id.spinner);
	    Button b = (Button)findViewById(R.id.saveBtn);
	    module = (EditText)findViewById(R.id.module_entry);
	    room = (EditText)findViewById(R.id.room_entry);
	    startPicker = (Button)findViewById(R.id.pickStartTime);
	    endPicker = (Button)findViewById(R.id.pickEndTime);
	    cancelBtn = (Button)findViewById(R.id.closeBtn);
	    lecturer = (EditText)findViewById(R.id.lecturer_entry);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.day_array, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);
	    Intent i = getIntent();
	    if(i.hasExtra("TDATA"))
	    {
	    temp = i.getStringArrayExtra("TDATA");
	    String day = temp[0];
	    
	    spinner.setSelection(getDayInt(day));
	    module.setText(temp[1]);
	    lecturer.setText(temp[2]);
	    room.setText(temp[3]);
	    startPicker.setText(temp[4]);
	    endPicker.setText(temp[5]);
	    update = true;
	    _id = temp[6];
	    }
	    if (i.hasExtra("GROUP_NUMBER"))
	    {
	    	int num = i.getIntExtra("GROUP_NUMBER",0);
	    	spinner.setSelection(num);
	    }
	 
	    
	    
	   
	    
	    startPicker.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(STIME_DIALOG_ID);
			}
		});
	    endPicker.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(ETIME_DIALOG_ID);
			}
		});
	    
	    // get the current time
        final Calendar c = Calendar.getInstance();
        startHour = c.get(Calendar.HOUR_OF_DAY);
        startMin = c.get(Calendar.MINUTE);
	    cancelBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
				
			}
		});
	    b.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(module.getText().toString().equals(""))
				{
					makeAlert("Module");
				}
				else if(lecturer.getText().toString().equals(""))
				{
					makeAlert("Lecturer");
				}
				else if(room.getText().toString().equals(""))
				{
					makeAlert("Room");
				}
				else if(startPicker.getText().toString().equals("Start Time"))
				{
					makeAlert("Start Time");
				}else if(endPicker.getText().toString().equals("End Time"))
				{
					makeAlert("End Time");
				}
				else
				{		
					events = new TimeTableData(v.getContext()); 
				      try {
				    	  day = spinner.getSelectedItemPosition()+1;
				    	  if(!update)
				    		  addEvent(day, module.getText().toString(), lecturer.getText().toString(), room.getText().toString(), startPicker.getText().toString(), endPicker.getText().toString());
				    	  else
				    		  updateEvent(_id,day, module.getText().toString(), lecturer.getText().toString(), room.getText().toString(), startPicker.getText().toString(), endPicker.getText().toString());
				      } finally {
				         events.close(); 
				      }
				  
				      setResult(RESULT_OK);
				      finish();
				}
				
			}
		});
	    
	    
	}
	private void makeAlert(String s)
	{
		AlertDialog.Builder alertbox = new AlertDialog.Builder(AddClass.this);
    	alertbox.setTitle("Error");
        alertbox.setMessage("Please Enter a Value for "+s);
        alertbox.setNeutralButton("Close", new DialogInterface.OnClickListener() {

            // Click listener on the neutral button of alert box
            public void onClick(DialogInterface arg0, int arg1) {

                
            }
        });
        alertbox.show();
		
		
	}
	
	
	
	// the callback received when the user "sets" the time in the dialog
	private TimePickerDialog.OnTimeSetListener sTimeSetListener =
	    new TimePickerDialog.OnTimeSetListener() {
	        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
	            startHour = hourOfDay;
	            startMin = minute;
	            updatedisplay("start");
	        }
	    };
    private TimePickerDialog.OnTimeSetListener eTimeSetListener =
	    new TimePickerDialog.OnTimeSetListener() {
	        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
	            endHour = hourOfDay;
	            endMin = minute;
	            updatedisplay("end");
	        }
	    };
    private void updatedisplay(String time)
    {
    	if(time == "start")
    	{
    		
    		startPicker.setText(new StringBuilder()
    		.append(pad(startHour))
    		.append(":")
    		.append(pad(startMin)));
    	}
    	else
    		endPicker.setText(new StringBuilder()
    		.append(pad(endHour))
    		.append(":")
    		.append(pad(endMin)));
    	 
    	
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case STIME_DIALOG_ID:
            return new TimePickerDialog(this,
                    sTimeSetListener, startHour, startMin, false);
        case ETIME_DIALOG_ID:
        	 return new TimePickerDialog(this,
	                    eTimeSetListener, endHour, endMin, false);
        }
        return null;
    }
	private static String pad(int c) {
	    if (c >= 10)
	        return String.valueOf(c);
	    else
	        return "0" + String.valueOf(c);
	}
	private void addEvent(int day,String module,String lecturer,String Room,String startTime,String endTime) {
        // Insert a new record into the Events data source.
        // You would do something similar for delete and update.
        SQLiteDatabase db = events.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DAY, day);
        values.put(MODULE, module);
        values.put(LECTURER, lecturer);
        values.put(ROOM,Room);
        values.put(TIMESTART,startTime);
        values.put(TIMEEND, endTime);
        db.insertOrThrow(TABLE_NAME, null, values);
     }
	private void updateEvent(String id,int day,String module,String lecturer,String Room,String startTime,String endTime) {
	
		SQLiteDatabase db = events.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DAY, day);
        values.put(MODULE, module);
        values.put(LECTURER, lecturer);
        values.put(ROOM,Room);
        values.put(TIMESTART,startTime);
        values.put(TIMEEND, endTime);
	    db.update(TABLE_NAME, values, "_ID=?", new String[] {id});
				
		
	}
	private int getDayInt(String day)
	{
		String[] d = new String[] {"Monday","Tuesday","Wednesday","Thursday","Friday"};
		for(int i = 0; i < d.length;++i)
		{
			if(day.equals(d[i]))
			{
				return i;
			}
		}
		
		return 0;
		
		
	}
}
